package com.athay.diary.service.impl;

import com.athay.diary.entity.Diary;
import com.athay.diary.entity.Role;
import com.athay.diary.entity.User;
import com.athay.diary.mapper.DiaryMapper;
import com.athay.diary.service.DiaryService;
import com.athay.diary.service.UserService;
import com.athay.diary.util.SecurityUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
@Transactional
public class DiaryServiceImpl extends ServiceImpl<DiaryMapper, Diary> implements DiaryService {

    private final UserService userService;

    public DiaryServiceImpl(UserService userService) {
        this.userService = userService;
    }

    @Override
    public List<Diary> listByCurrentUser(Authentication authentication) {
        User currentUser = SecurityUtils.getCurrentUser(authentication);
        if (Objects.equals(currentUser.getRole(), Role.ADMIN.getValue())) {
            // 管理员查看所有未隐藏的日记（包括被隐藏的？根据需求调整，此处允许管理员查看所有）
            return list();
        }
        // 普通用户只能查看自己未隐藏的日记
        return lambdaQuery()
                .eq(Diary::getUserId, currentUser.getId())
                .list();
    }

    @Override
    public void deleteById(Long diaryId, Authentication authentication) {
        User currentUser = SecurityUtils.getCurrentUser(authentication);
        Diary diary = getById(diaryId);
        if (diary == null) {
            throw new IllegalArgumentException("日记不存在");
        }
        if (!Objects.equals(currentUser.getRole(), Role.ADMIN.getValue()) && !diary.getUserId().equals(currentUser.getId())) {
            throw new AccessDeniedException("无权删除他人日记");
        }
        removeById(diaryId);
    }

    @Override
    public void update(Diary diary, Authentication authentication) {
        User currentUser = SecurityUtils.getCurrentUser(authentication);
        Diary existDiary = getById(diary.getId());
        if (existDiary == null) {
            throw new IllegalArgumentException("日记不存在");
        }
        if (!Objects.equals(currentUser.getRole(), Role.ADMIN.getValue()) && !existDiary.getUserId().equals(currentUser.getId())) {
            throw new AccessDeniedException("无权修改他人日记");
        }
        diary.setUpdateTime(new Date());
        updateById(diary);
    }

}